const indexApi = require("../api/indexApi")
const resourceApi = require("../api/resourceApi")
const apiUtil = require("../utils/apiUtil")
const process = require("child_process")

module.exports = {
    simpleArticleList(req, res, next) {
        indexApi.simpleArticleList(1, 5).then(data => {
            res.render('index', {
                data: data.records,
                online: req.app.get("online"),
            });
        }).catch(err => {
            res.redirect("/rpcError")
        })
    },
    listPage(req, res, next) {
        let currentPage = req.params.currentPage || 1
        let pageSize = req.params.pageSize || 5
        if (currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize <= 0) {
            pageSize = 5;
        }
        indexApi.articleList(currentPage, pageSize).then(data => {
            res.render('list', {
                data: data.records,
                currentPage,
                pageSize,
            });
        }).catch(err => {
            res.redirect("/rpcError")
        })
    },
    resource(req, resp) {
        resourceApi.list().then(data => {
            resp.render("resource", { data })
        }).catch(err => {
            res.redirect("/rpcError")
        })
    },
    page(req, resp) {
        console.log(req.params.id);//获取参数
        //远程调用
        indexApi.getArticleById(req.params.id).then(data => {
            //返回page页面
            resp.render("page", { data })
        }).catch(err => {
            res.redirect("/rpcError")
        })
    },
    rpcError(req, resp)  {
        console.log("状态"+req.app.get("isRestartTomcat"))
        if(req.app.get("isRestartTomcat")){
            resp.json(apiUtil.REMOTE_API_RESTAR);
            return false;
        }
        //远程调用失败，容错处理
        req.app.set("isRestartTomcat",true);
        process.exec("nohup java -jar /usr/local/java/blog-0.0.1-SNAPSHOT.jar &", (err, stdout, stderr) => {
          console.log(stdout)
          req.app.set("isRestartTomcat",false);
        })
        resp.json(apiUtil.CALL_REMOTE_API_EXCEPTION)
      }

}